﻿using System;
using System.IO;
using System.Text;
using System.Reflection;
using System.Runtime.Serialization.Json;

namespace IMDBApi.Contracts.Entities
{
    /// <summary>
    /// A class which provides functions to deserialize json data.
    /// </summary>
    public static class JSONSerializer
    {
        /// <summary>
        /// Deserialize a JSON-encoded data into a new instance of Type T.
        /// </summary>
        /// <typeparam name="T">Target Type.</typeparam>
        /// <param name="json">JSON-encoded data.</param>
        /// <returns>The target type.</returns>
        public static T Deserialize<T>(string json)
        {
            if (json == string.Empty)
            {
                throw new Exception(MethodInfo.GetCurrentMethod().Name + ": A json string is required.");
            }
            else
            {
                var stream = new MemoryStream(Encoding.UTF8.GetBytes(json));
                var serializer = new DataContractJsonSerializer(typeof(T));
                var result = (T)serializer.ReadObject(stream);

                return result;
            }
        }
    }
}
